(function(window) {
  'use strict';

  var App = window.App || {};
  var $ = window.jQuery;

  function FormHandler(selector) {
    if (!selector) {
      throw new Error('No selector provided!');
    }
    this.$formElement = $(selector);
    if (this.$formElement.length === 0) {
      throw new Error('Could not find element with selector: ' + selector);
    }
  }
  FormHandler.prototype.addSubmitHandler = function(fn) {
    console.log('Setting submit handler for form');
    this.$formElement.on('submit', function(event) {
      event.preventDefault();
      var data = {};
      $(this).serializeArray().forEach(function(item) {
        data[item.name] = item.value;
        console.log(item.name + ' is ' + item.value);
      })
      fn(data);
      this.reset();
      this.elements[0].focus();
    });
  }

  FormHandler.prototype.sliderRangeHandler = function() {
    $('[data-coffee-order="rating"]').on('change', function(event){
      $(this).find('span').html(event.target.value);
    });

  }

  FormHandler.prototype.addInputHandler = function(fn) {
    this.$formElement.on('input', '[name="emailAddress"]', function(event) {
      var emailAddress = event.target.value;
      var message = '';
      if(fn(emailAddress)){
        event.target.setCustomValidity('');
      } else {
        message = emailAddress + ' is not an authorized email address!';
        event.target.setCustomValidity(message);
      }
    });
  }

  FormHandler.prototype.addCoffeeNameHandler = function(fn,max) {
        console.log('Setting input letter number for form');
        this.$formElement.on('input','[name="coffee"]', function(event){
          var coffee = event.target.value;
          var message = '';
          if(fn(coffee, max)){
            event.target.setCustomValidity('');
          } else {
            message = coffee + ' is more than '+ max +' letters!';
            event.target.setCustomValidity(message);
          }
        });
  }

  App.FormHandler = FormHandler;
  window.App = App;
})(window);
